package com.link.base.tencent.corpwx.access.service;

import com.alibaba.fastjson.JSONObject;
import com.link.core.cllog.LCLogger;
import com.link.base.tencent.corpwx.access.model.MsgBasic;
import com.link.base.wechat.basic.util.MsgUtil;
import com.link.base.wechat.basic.aes.WXBizMsgCrypt;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;

/**
 * 消息事件服务
 *
 * @author 欧阳振强
 * @date 2019/1/2
 */
@Service
public class CorpWxAccessServiceImpl extends BasicServiceImpl<MsgBasic> implements CorpWxAccessService {

    @Override
    public JSONObject parseEventXml(HttpServletRequest request, String corpId, String token, String aesKey) throws Exception {
        // 提取文件流
        String encXml = MsgUtil.getRequestStr(request);
        LCLogger.info().withMessageKey("auth").withMessage("解密前整体密文->" + encXml).flush();
        // 消息体签名，用于验证消息体的正确性
        String msg_signature = request.getParameter("msg_signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 加密的字符串,用于验证URL有效性，需要Url decode
        String echostr = request.getParameter("echostr");
        LCLogger.info().withMessageKey("auth").withMessage("msg_signature->" + msg_signature + "; timestamp->"
                + timestamp + "; nonce->" + nonce + "; echostr->" + echostr).flush();
        // 加解密操作对象
        WXBizMsgCrypt pc = new WXBizMsgCrypt(token, aesKey, corpId);
        // 返回给企业微信服务器的结果
        JSONObject result = new JSONObject();
        String resultStr;
        // 首次验证url需要解析echo str
        if (StringUtils.isNotBlank(echostr)) {
            resultStr = pc.verifyUrl(msg_signature, timestamp, nonce, echostr);
            result.put("verifyFlag",resultStr);
        } else {
            resultStr = pc.decryptMsg(msg_signature, timestamp, nonce, encXml);
            result.put("busFlag",resultStr);
        }
        LCLogger.info().withMessageKey("auth").withMessage("解密后明文->" + resultStr).flush();
        return result;
    }
}
